//
//  BApplyForMoneyVC.m
//  DistributorAB
//
//  Created by LZY on 2019/10/8.
//  Copyright © 2019 主事丫环. All rights reserved.
//

// 扫码申请补助金VC

#import "BApplyForMoneyVC.h"
#import "BApplyForMoneyDetailCell.h"
#import "BApplyForMoneyReasonCell.h"
#import "BGoodsInfoModel.h"
#import "BApplyForMoneySuccessView.h"//提交成功提示窗

@interface BApplyForMoneyVC () <UITableViewDelegate,UITableViewDataSource,BApplyForMoneySuccessViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *btnApply;//申请按钮
@property (nonatomic, assign) BOOL showReason;//是否显示申请原因
@property (nonatomic, strong) BApplyForMoneyReasonCell *cellReason;//损坏描述cell
@property (nonatomic, strong) BGoodsInfoModel *goodsModel;//申请补助金配件详情model
@end

@implementation BApplyForMoneyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"申请补助";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    self.view.backgroundColor = kColorWithHex(0xf2f2f2);
    
    self.showReason = YES;
    [self setupViewAction];
    [self requestData];
}
#pragma mark - 界面布局方法
- (void)setupViewAction{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNaviHeight, kScreen_Width, kScreen_Height - kNaviHeight - TabbarSafeBottomMargin-100) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = kColorWithHex(0xf2f2f2);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[BApplyForMoneyDetailCell class] forCellReuseIdentifier:NSStringFromClass([BApplyForMoneyDetailCell class])];
    [_tableView registerClass:[BApplyForMoneyReasonCell class] forCellReuseIdentifier:NSStringFromClass([BApplyForMoneyReasonCell class])];
    
    _btnApply = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnApply.frame = CGRectMake(26, kScreen_Height - 40 - 48 - TabbarSafeBottomMargin, kScreen_Width - 52, 48);
    [_btnApply setBackgroundColor:kColorWithHex(0x70be68)];
    [_btnApply setTitle:@"提交" forState:UIControlStateNormal];
    [_btnApply setTitleColor:kColorWithHex(0xffffff) forState:UIControlStateNormal];
    _btnApply.titleLabel.font = [UIFont systemFontOfSize:16];
    _btnApply.layer.cornerRadius = 4;
    _btnApply.layer.masksToBounds = YES;
    [_btnApply addTarget:self action:@selector(btnApplyClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnApply];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isFromGrantDetail) {
        return self.grantDetailModel ? (self.showReason ? 2 : 1) : 0;
    }else{
        return self.goodsModel ? (self.showReason ? 2 : 1) : 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        BApplyForMoneyDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BApplyForMoneyDetailCell class]) forIndexPath:indexPath];
        cell.model = self.goodsModel;
        cell.grantDetailModel = self.grantDetailModel;
        return cell;
    }else if (indexPath.row == 1){
        BApplyForMoneyReasonCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BApplyForMoneyReasonCell class]) forIndexPath:indexPath];
        self.cellReason = cell;
        cell.grantDetailModel = self.grantDetailModel;
        return cell;
    }else{
        return [UITableViewCell new];
    }
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.goodsModel || self.grantDetailModel) {
        if (indexPath.row == 0) {
            return 440;
        }else if (indexPath.row == 1){
            return 146;
        }else{
            return 0;
        }
    }else{
        return 0;
    }
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.tableView.contentSize = CGSizeMake(0,700);
}
#pragma mark - BApplyForMoneySuccessViewDelegate
- (void)viewBtnOKClick{
    if (self.isFromGrantDetail) {
        if (self.navigationController.viewControllers.count > 3) {
            UIViewController *vc = [self.navigationController.viewControllers objectAtIndexSafe:1];
            [self.navigationController popToViewController:vc animated:YES];
        }
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma mark - 数据请求
- (void)requestData{
    if (self.codeStr.length > 0) {
        //扫码申请
        kWeakSelf;
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        
        if ([self.codeStr containsString:@"#"]) {
            self.codeStr = [self.codeStr stringByReplacingOccurrencesOfString:@"#" withString:@""];
        }
        
        [param setObject:self.codeStr.length > 0 ? self.codeStr : @"" forKey:@"data"];
        [NetWorkTool POST:scanQrCodeApplyMoney param:param success:^(id dic) {
            self.goodsModel = [BGoodsInfoModel mj_objectWithKeyValues:[dic objectForKey:@"data"]];
            [weakSelf.tableView reloadData];
        } other:^(id dic) {
            ShowToastWithText(dic[@"msg"]);
        } fail:^(NSError *error) {
            ShowToastWithText(@"获取数据失败");
        } needUser:YES];
    }
}
#pragma mark - 交互事件
//申请补助
- (void)btnApplyClickAction:(UIButton *)sender{
    
    if ([sender.titleLabel.text isEqualToString:@"提交"]){
        
        [self checkGrantApply];
        
    }
}
#pragma mark - 检测是否申请过补助金
- (void)checkGrantApply{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.goodsModel.qrcode forKey:@"qrcode"];
    kWeakSelf;
    [NetWorkTool POST:USER_CHECK_GRANT param:param success:^(id dic) {
        [weakSelf canApplyGrant];
        
    } other:^(id dic) {
        NSString *tip = dic[@"msg"];
        ShowToastWithText(tip);
        
    } fail:^(NSError *error) {
        
    } needUser:YES];
}
- (void)canApplyGrant{
    self.showReason = YES;
    [self.tableView reloadData];

    if(self.isFromGrantDetail){
        //重新申请
        [self reapplyForGrantWithReason:self.cellReason.applyReason];
    }else{
        //提交申请
        [self applyForGrantWithReason:self.cellReason.applyReason];
    }
    
}
#pragma mark - 提交申请补助金
- (void)applyForGrantWithReason:(NSString *)reason{
     //市县级--扫码申请补助金提交时没有校验配件是否过质保期（损坏时间shTime - 安装时间anTime 大于质保期 warranty 相减按月为单位后比较）不允许提交
    NSDictionary *param = @{
                        @"reason":NOTNIL(reason),
                        @"qrcode":NOTNIL(self.goodsModel.qrcode),
                    @"repUserId":NOTNIL(self.goodsModel.repairUser.Id)
                                   };
   
    if (self.goodsModel.shTime.length==0) {
        ShowToastWithText(@"没有损坏时间，无法提交");
        return;
    }
    NSString *monthStr = [self dateTimeDifferenceWithStartTime:self.goodsModel.shTime withEndTime:self.goodsModel.anTime];
    if (monthStr.integerValue >[self.goodsModel.warranty integerValue]) {
        ShowToastWithText(@"配件已过质保期");
        return;
    }
    
    NSString *jsonStr = [HFTools toJSONString:param];
    NSDictionary *jsonDic = [NSDictionary dictionaryWithObject:jsonStr forKey:@"data"];
    
    [NetWorkTool POST:applyForGrant param:jsonDic success:^(id dic) {
        BApplyForMoneySuccessView *viewSuccess = [[BApplyForMoneySuccessView alloc] init];
        viewSuccess.delegate = self;
        [viewSuccess showView];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        ShowToastWithText(@"提交失败，请稍后再试");
    } needUser:YES];
}
#pragma mark - 补助金详情的相关处理
- (void)setIsFromGrantDetail:(BOOL)isFromGrantDetail{
    _isFromGrantDetail = isFromGrantDetail;
    if (isFromGrantDetail) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self canApplyGrant];
            [self.tableView reloadData];
            
        });
    }
}
//重新申请
- (void)reapplyForGrantWithReason:(NSString *)reason{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:reason forKey:@"reason"];
    [param setObjectIfNotNil:self.grantID forKey:@"id"];
    [NetWorkTool POST:USER_REAPP_GRANTS param:param success:^(id dic) {
        BApplyForMoneySuccessView *viewSuccess = [[BApplyForMoneySuccessView alloc] init];
        viewSuccess.delegate = self;
        [viewSuccess showView];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        ShowToastWithText(@"提交失败，请稍后再试");
    } needUser:YES];
}
- (NSString *)dateTimeDifferenceWithStartTime:(NSString *)StartTime withEndTime:(NSString *)EndTime
{
    //创建两个日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
   
    NSDate *startDate = [dateFormatter dateFromString:StartTime];
    NSDate *endDate = [dateFormatter dateFromString:EndTime];
    
    //利用NSCalendar比较日期的差异
    NSCalendar *calendar = [NSCalendar currentCalendar];
    /**
     * 要比较的时间单位,常用如下,可以同时传：
     *    NSCalendarUnitDay : 天
     *    NSCalendarUnitYear : 年
     *    NSCalendarUnitMonth : 月
     *    NSCalendarUnitHour : 时
     *    NSCalendarUnitMinute : 分
     *    NSCalendarUnitSecond : 秒
     */
    NSCalendarUnit unit = NSCalendarUnitMonth;//只比较 月份 差异
    //比较的结果是NSDateComponents类对象
    NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
    NSString *str  =[NSString stringWithFormat:@"%ld",(long)delta.month] ;
    return str;
    
}
@end
